<template>
  <div class="payment-record">
    <!-- 搜索区域 -->
    <div class="search-section" style="height: 85px;">
      <el-form :model="dialogForm" ref="dialogForm">
        <el-row :gutter="10">
          <el-col :span="4">
            <el-form-item label="年度:" class="inline-form-item">
              <el-select v-model="dialogForm.year" clearable placeholder="全部">
                <el-option label="全部" value=""></el-option>
                <el-option
                  v-for="year in yearOptions"
                  :key="year"
                  :label="`${year}年`"
                  :value="year"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="客户名称:" class="inline-form-item">
              <el-autocomplete
                v-model="dialogForm.clientName"
                :fetch-suggestions="queryClientAsync"
                placeholder="请输入客户名称"
                @select="handleClientSelect">
              </el-autocomplete>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="合同编号:" class="inline-form-item">
              <el-input
                v-model="dialogForm.contractCode"
                placeholder="请输入合同编号"
                clearable>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="类别:" class="inline-form-item">
              <el-select v-model="dialogForm.contractType" clearable placeholder="请选择类别">
                <el-option label="全部" value=""></el-option>
                <el-option label="在线运维" value="在线运维"></el-option>
                <el-option label="在线建设" value="在线建设"></el-option>
                <el-option label="污水运维" value="污水运维"></el-option>
                <el-option label="污水建设" value="污水建设"></el-option>
                <el-option label="宝马在线" value="宝马在线"></el-option>
                <el-option label="宝马污水" value="宝马污水"></el-option>
                <el-option label="其他" value="其他"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="合同名称:" class="inline-form-item">
              <el-input
                v-model="dialogForm.contractName"
                placeholder="请输入合同名称"
                clearable>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <!-- <el-link type="primary" style="margin-left: 20px">本年约定回款-合同金额/回款周期</el-link> -->
          </el-col>
        </el-row>
      </el-form>
    </div>

    <!-- 表格区域 -->
    <el-table
      :data="tableData"
      border
      style="width: 100%"
      @selection-change="handleSelectionChange"
      size="mini"
      :header-cell-style="{background:'#f5f7fa',color:'#606266',fontSize:'14px',fontWeight:'600',textAlign:'center'}"
      :cell-style="{fontSize:'12px',padding:'6px 0',textAlign:'center'}"
      height="650"
    >
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column prop="contractCode" label="合同编号" width="180">
        <template slot-scope="scope">
          <el-link type="primary" @click="handlePaymentDetail(scope.row.contractCode)">{{ scope.row.contractCode }}</el-link>
        </template>
      </el-table-column>
      <el-table-column prop="year" label="年度" width="100"></el-table-column>
      <el-table-column prop="contractType" label="类别" width="120"></el-table-column>
      <el-table-column prop="clientName" label="客户名称" width="150"></el-table-column>
      <el-table-column prop="contractName" label="合同名称" width="150"></el-table-column>

      <el-table-column label="开始时间" width="180">
          <template slot-scope="scope">
            {{ formatDate(scope.row.startDate) }}
          </template>
        </el-table-column>
        <el-table-column label="到期时间" width="180">
          <template slot-scope="scope">
            {{ scope.row.endDate ? formatDate(scope.row.endDate) : '--' }}
          </template>
        </el-table-column>
      <el-table-column prop="manager" label="客户经理" width="100"></el-table-column>
      <el-table-column prop="effectiveAmount" label="合同金额" width="120"></el-table-column>

      <el-table-column label="21年回款" prop="year2021Payment" width="120" class-name="scroll-column">
        <template v-slot="{ row }">
          {{ row.year2021Payment || '--' }}
        </template>
      </el-table-column>
      <el-table-column label="22年回款" prop="year2022Payment" width="120" class-name="scroll-column">
        <template v-slot="{ row }">
          {{ row.year2022Payment || '--' }}
        </template>
      </el-table-column>
      <el-table-column label="23年回款" prop="year2023Payment" width="120" class-name="scroll-column">
        <template v-slot="{ row }">
          {{ row.year2023Payment || '--' }}
        </template>
      </el-table-column>
      <el-table-column label="24年回款" prop="year2024Payment" width="120" class-name="scroll-column">
        <template v-slot="{ row }">
          {{ row.year2024Payment || '--' }}
        </template>
      </el-table-column>
      <el-table-column label="25年回款" prop="year2025Payment" width="120" class-name="scroll-column"></el-table-column>
      <el-table-column label="26年回款" prop="year2026Payment" width="120" class-name="scroll-column">
        <template v-slot="{ row }">
          {{ row.year2026Payment || '--' }}
        </template>
      </el-table-column>
      <el-table-column label="27年回款" prop="year2027Payment" width="120" class-name="scroll-column">
        <template v-slot="{ row }">
          {{ row.year2027Payment || '--' }}
        </template>
      </el-table-column>
      <el-table-column label="28年回款" prop="year2028Payment" width="120" class-name="scroll-column">
        <template v-slot="{ row }">
          {{ row.year2028Payment || '--' }}
        </template>
      </el-table-column>
      <el-table-column label="29年回款" prop="year2029Payment" width="120" class-name="scroll-column">
        <template v-slot="{ row }">
          {{ row.year2029Payment || '--' }}
        </template>
      </el-table-column>
      <el-table-column label="30年回款" prop="year2030Payment" width="120" class-name="scroll-column">
        <template v-slot="{ row }">
          {{ row.year2030Payment || '--' }}
        </template>
      </el-table-column>
      <el-table-column prop="unfinishedOutput" label="未回款金额" width="120"></el-table-column>
    </el-table>
    <!-- 分页 -->
    <pagination
            v-show="total > 0"
            :total="total"
            :page.sync="formData.pageNum"
            :limit.sync="formData.pageSize"
            @pagination="getList"
          />
    <el-dialog
      :visible="detailVisible"
      title="回款明细"
      width="60%"
      @close="detailVisible = false"
    >
      <el-table :data="paymentDetails" border style="width: 100%; margin-top: 20px">
        <el-table-column label="回款月份" width="180">
          <template slot-scope="scope">
            {{ (scope.row.paymentMonth) }}
          </template>
        </el-table-column>
        <el-table-column label="回款时间" width="180">
          <template slot-scope="scope">
            {{ formatDate(scope.row.paymentDate) }}
          </template>
        </el-table-column>
        <el-table-column prop="payment" label="回款金额" width="120" />
        <el-table-column label="发票信息" width="200">
          <template slot-scope="scope">
            {{ scope.row.invoiceId ? scope.row.invoiceId : '无发票' }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="100">
          <template slot-scope="scope">
            <el-button type="primary" size="small" @click="handleEdit(scope.row)">修改</el-button>
          </template>
        </el-table-column>


      </el-table>
    </el-dialog>

        <el-dialog
          title="修改回款金额"
          :visible="editDialogVisible"
          width="30%"
          @close="handleCancelEdit">
          <el-form :model="{ paymentAmount: invoice.invoiceAmount }" label-width="80px">
            <el-form-item label="回款金额">
              <el-input type="number" v-model="invoice.invoiceAmount" placeholder="请输入回款金额" oninput="this.value = this.value.replace(/[^\d]/g, '')"></el-input>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="handleCancelEdit">取消</el-button>
            <el-button type="primary" @click="handleConfirmEdit">确定</el-button>
          </div>
        </el-dialog>

  </div>

</template>

<script>

import { list, Clientlist,queryReturnValue } from "@/api/monitor/contract";
import { editInvoiceAmount } from "@/api/monitor/invoice";

export default {
  name: 'PaymentRecord',

  data() {
    return {
      editDialogVisible: false,
      clientList: [],
      paymentDetails: [], // 初始化回款数据数组

      dialogForm: {
        clientName:"",
        clientCode:"",
        year: '',
        contractCode: "",
        contractType: "",
        contractName: "",
      },

      // 选项数据
      yearOptions: [2024, 2023, 2022, 2021, 2020,2025,2027],
      typeOptions: ['在线运维', '在线设设', '污水运维', '污水设设'],
      customerTypeOptions: ['政府', '企业', '个人'],
      customerOptions: ['客户A', '客户B', '客户C', '客户D', '客户E'],
      managerOptions: ['小张', '小李', '小王', '小赵'],
      paymentStatusOptions: ['已回款', '部分回款', '未回款'],

      invoice:{
        invoiceAmount: 0,
        returnValueId: 0,
        invoiceId: 0,
        oldInvoiceAmount: 0,
        contractCode: '',
        hasInvoice: 0,
      },

      // 表格数据
      tableData: [],
// 搜索表单数据
      formData: {
              pageNum: 1,
              pageSize: 15,
              year: "",
              clientName: "",
              contractCode: "",
              contractType: "",
              contractName: "",
            },
      // 分页
      total: 113,

      // 选中的行
      selectedRows: [],
      detailVisible: false,
    }
  },
  created() {
      this.getList();
      this.getClientList();
  },

  methods: {
    // 获取列表数据
    getClientList() {
      Clientlist().then(response => {
        this.clientList = response
        // this.tableData = response.rows;
        // this.total = response.total;

      });
    },
    // 客户选择处理
    handleClientSelect(item) {
      this.dialogForm.clientCode = item.data.code;
    },
    // 客户名称搜索
    queryClientAsync(queryString, cb) {

      const results = queryString
        ? this.clientList.filter((client) =>
            client.name.toLowerCase().includes(queryString.toLowerCase())
          )
        : this.clientList;
      cb(results.map((client) => ({ value: client.name, data: client })));
    },
    // 获取列表数据
    getList() {
      this.loading = true;
      list(this.formData).then(response => {
        console.log(5555555,response)
        this.tableData = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 搜索
    handleSearch() {
      this.formData.pageNum = 1;
      this.formData.year = this.dialogForm.year;
      this.formData.clientName = this.dialogForm.clientName;
      this.formData.contractCode = this.dialogForm.contractCode;
      this.formData.contractType = this.dialogForm.contractType;
      this.formData.contractName = this.dialogForm.contractName;
      this.getList();
      console.log('搜索条件:', this.formData)
    },


    // 新增
    handleAdd() {
      // 实现新增逻辑
      console.log('新增记录')
    },

    // 修改
    handleEdit(row) {
      this.editDialogVisible = true;
      console.log('修改记录:', row);
      this.invoice.invoiceAmount = row.payment; // 假设回款金额字段为paymentAmount
      this.invoice.invoiceId = row.invoiceId;//发票id
      this.invoice.returnValueId = row.id;//回款id
      this.invoice.contractCode = row.contractCode;//合同编号
      this.invoice.hasInvoice = row.hasInvoice;//是否有发票
      this.invoice.oldInvoiceAmount = row.payment;//之前的回款金额
    },

    handleConfirmEdit() {

      // 这里添加实际的修改逻辑，例如调用API更新数据
      console.log('确认修改，新回款金额:', this.invoice);
      //发起后端请求
      editInvoiceAmount(this.invoice).then(response => {

        if (response === 3) {
            this.$message.error('回款金额大于合同金额');
            return false ;
          } else if (response === 4) {
            this.$message.error('未达到月份回款要求');
            return false ;
          }else if (response === 5) {
            this.$message.error('回款金额大于发票可用金额');
            return false ;
          } else {
            console.log(5555555,response)
            this.handlePaymentDetail(this.invoice.contractCode);
            this.getList();
            this.loading = false;
          }
      });

      this.editDialogVisible = false;

    },

    handleCancelEdit() {
      this.editDialogVisible = false;
    },


    // 选择行
    handleSelectionChange(val) {
      this.selectedRows = val
    },

    // 分页
    handleSizeChange(val) {
      this.pageSize = val
      // 重新加载数据
    },

    handleCurrentChange(val) {
      this.currentPage = val
      // 重新加载数据
    },

    async handlePaymentDetail(contractCode) {
      try {
        // 请求后台获取回款信息
        const response = await queryReturnValue({ contractCode: contractCode });
        console.log(666666,response)
        this.paymentDetails = response; // 存储后台返回的rows数组数据
        this.detailVisible = true;
      } catch (error) {
        this.$message.error('获取回款信息失败：' + (error.message || '未知错误'));
      }
    },
    formatDate(dateStr) {
      const date = new Date(dateStr);
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      const seconds = String(date.getSeconds()).padStart(2, '0');
      return `${year}-${month}-${day} `;
    }
  }
}
</script>

<style scoped>

.inline-form-item {
  display: flex;
  align-items: center;
  line-height: 0px;
  white-space: nowrap;
}
.inline-form-item .el-form-item__label {
  width: auto;
  margin-right: 10px;
}
.el-form-item--medium .el-form-item__label {
  line-height: 0px !important;
}
.inline-form-item .el-form-item__content {
  flex: 1;
}
.payment-record {
  padding: 20px;
}

.search-section {
  background: #fff;
  padding: 20px;
  margin-bottom: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, .12);
}

.el-row {
  margin-bottom: 20px;
}

.el-select {
  width: 100%;
}

.el-date-editor.el-input {
  width: 100%;
}

.pagination-section {
  margin-top: 20px;
  text-align: right;
}

.el-button {
  margin-right: 10px;
}

.el-link {
  font-size: 14px;
}

/* 表格样式优化 */
.el-table {
  margin-top: 20px;
}

.el-table th {
  background-color: #f5f7fa;
  color: #606266;
}

.el-table td {
  padding: 8px 0;
}

/* 链接样式 */
.el-link {
  font-weight: normal;
}

/* 按钮组样式 */
.operation-buttons {
  white-space: nowrap;
}

.operation-buttons .el-button {
  padding: 3px 0;
  margin: 0 5px;
}
.scroll-container {
  overflow-x: auto;
}
.scroll-column {
  min-width: 120px;
}
</style>
